<style scoped>
    .time{
        color:white;
        font-size: 14px;
        font-weight: bold;
        padding:3px 13px 3px 3px;
    }
    .content{
        padding-left: 5px;
        line-height:20px;
        background-color:#eee;
        padding:5px;
    }
    .badge-alone{
        background: #f56a00;
    }

    /**********************Layout*********************/
    .layout{
        border: 1px solid #d7dde4;
        background: #f5f7f9;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
    }
    .layout-header-bar{
        background: #fff;
        box-shadow: 0 1px 1px rgba(0,0,0,.1);
    }
    .layout-logo-left{
        width: 90%;
        height: 30px;
        background: #5b6270;
        border-radius: 3px;
        margin: 15px auto;
    }
    .menu-icon{
        transition: all .3s;
    }
    .rotate-icon{
        transform: rotate(-90deg);
    }
    .menu-item span{
        display: inline-block;
        overflow: hidden;
        width: 69px;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: bottom;
        transition: width .2s ease .2s;
    }
    .menu-item i{
        transform: translateX(0px);
        transition: font-size .2s ease, transform .2s ease;
        vertical-align: middle;
        font-size: 16px;
    }
    .collapsed-menu span{
        width: 0px;
        transition: width .2s ease;
    }
    .collapsed-menu i{
        transform: translateX(5px);
        transition: font-size .2s ease .2s, transform .2s ease .2s;
        vertical-align: middle;
        font-size: 22px;
    }
    /**********************Layout*********************/
</style>
<template>
    <div class="layout">
        <Layout>
            <Sider ref="side1" hide-trigger collapsible :collapsed-width="320" v-model="isCollapsed" width="900" :style="{margin: '10px 0px 10px 10px', background: '#fff', minHeight: '260px'}">
                <Card>
                    <p slot="title">
                        <Icon type="ios-film-outline"></Icon>
                        里程碑
                    </p>
                    <br>
                    <Row :gutter="8">
                        <Col span="3">&nbsp;</Col>
                        <Col span="18">
                            <Input v-model="keywords" @keyup.enter.native="handleSearch(1)" placeholder="请输入关键字">
                                <Icon type="ios-search-strong" slot="prepend" style="padding:0px 10px;"></Icon>
                            </Input>
                        </Col>
                        <Col span="3">&nbsp;</Col>
                    </Row>
                    <br>
                    <br>
                    <Row :gutter="8">
                        <Col span="1">&nbsp;</Col>
                        <Col span="22">
                            <Timeline>
                                <TimelineItem v-for="(item, index) in timesdata" :key="index">
                                    <div>
                                        <Badge :count="item.sn" class="badge-alone">
                                            <p class="time" @click="handleFormdata(item.roadmapsid,item.thetime,item.content,item.participants,item.picture,item.zipfile,item.creator,item.sn,item.signstatus)" style="cursor:pointer;">
                                                {{item.thetime}} <font style="font-style:italic;padding-left:10px;font-weight:normal;color:#eee;">by</font> {{item.creator}}
                                            </p>
                                        </Badge>
                                        <Alert v-show="!isCollapsed" type="success" show-icon v-if="item.signstatus=='已确认'" style="float:right;top:20px;">达成一致</Alert>
                                        <Alert v-show="!isCollapsed" type="warning" show-icon v-if="item.signstatus=='未确认'" style="float:right;top:20px;">确认中</Alert>

                                        <Form v-show="!isCollapsed" class="content" :label-width="80">
                                            <FormItem label="内容描述：">
                                                <p>
                                                    <span v-html="item.content"></span>
                                                </p>
                                            </FormItem>
                                            <FormItem v-show="!isCollapsed" label="内容截图：" v-if="(item.picture!=null && item.picture!='undefined' && item.picture.length>0)">
                                                <p>
                                                    <Poptip placement="right">
                                                        <img style="max-height:250px;max-width:100%;cursor:pointer;" :src="serverpath + item.picture"/>
                                                        <div class="api" slot="content">
                                                            <img style="max-height:750px;max-width:1000px;" :src="serverpath + item.picture"/>
                                                        </div>
                                                    </Poptip>
                                                </p>
                                                <p>
                                                    <Button slot="append" type="success" size="small" style="margin-right:8px;" @click="handleDownload(serverpath + item.picture)">
                                                        <Icon type="android-folder"></Icon> 下载并打开
                                                    </Button>
                                                </p>
                                            </FormItem>
                                            <FormItem label="文件下载：" v-if="(item.zipfile!=null && item.zipfile!='undefined' && item.zipfile.length>0)">
                                                <p style="font-style: italic;text-decoration:underline;">
                                                    {{item.zipfile?item.zipfile.replace('data/roadmaps/',''):''}}
                                                </p>
                                                <p>
                                                    <Button slot="append" type="success" size="small" style="margin-right:8px;" @click="handleDownload(serverpath + item.zipfile)">
                                                        <Icon type="android-folder"></Icon> 下载并打开
                                                    </Button>
                                                    <Button slot="append" type="primary" size="small" @click="handleOpenfile">
                                                        <Icon type="android-open"></Icon> 打开文件夹
                                                    </Button>
                                                </p>
                                            </FormItem>
                                            <FormItem v-show="!isCollapsed" label="确认情况：" v-if="(item.participants!=null && item.participants.length>0)">
                                                <p>
                                                    <ButtonGroup style="margin-right:10px;" size="small" v-for="(participant, index2) in item.participants.split(';')" :key="index2">
                                                        <Button>{{participant.split('-')[0]}}</Button>
                                                        <Button type="success" v-if="participant.split('-')[1]=='已确认'">
                                                            <Icon type="checkmark-round"></Icon>
                                                        </Button>
                                                        <Button type="warning" v-if="participant.split('-')[1]=='未确认' && currusername==participant.split('-')[0]" @click="handleConfirm(item.roadmapsid,item.participants,participant.split('-')[0])">
                                                            <Icon type="help"></Icon>
                                                        </Button>
                                                        <Button v-if="participant.split('-')[1]=='未确认' && currusername!=participant.split('-')[0]">
                                                            <Icon type="help"></Icon>
                                                        </Button>
                                                    </ButtonGroup>
                                                </p>
                                            </FormItem>
                                        </Form>

                                        <div v-show="isCollapsed">
                                            <p>
                                                <span v-if="isCollapsed && item.content.length>45" v-html="item.content.substring(0,45) + '......'"></span>
                                                <span v-if="isCollapsed && item.content.length<=45" v-html="item.content"></span>
                                            </p>
                                            <p v-if="(item.zipfile!=null && item.zipfile!='undefined' && item.zipfile.length>0)" style="font-style: italic;text-decoration:underline;">
                                                {{item.zipfile?item.zipfile.replace('data/roadmaps/',''):''}}
                                            </p>
                                            <p v-if="(item.zipfile!=null && item.zipfile!='undefined' && item.zipfile.length>0)">
                                                <Button slot="append" type="success" size="small" style="margin-right:8px;" @click="handleDownload(serverpath + item.zipfile)">
                                                    <Icon type="android-folder"></Icon> 下载并打开
                                                </Button>
                                                <Button slot="append" type="primary" size="small" @click="handleOpenfile">
                                                    <Icon type="android-open"></Icon> 打开文件夹
                                                </Button>
                                            </p>
                                        </div>

                                        <Modal
                                            v-model="showImgModal"
                                            width="auto"
                                            class-name="vertical-center-modal">
                                            <img :src="imgModalPic" style="max-width:1000px;max-height:700px;"/>
                                        </Modal>

                                    </div>
                                </TimelineItem>
                            </Timeline>
                        </Col>
                        <Col span="1">&nbsp;</Col>
                    </Row>
                </Card>
            </Sider>
            <Layout>
                <Content :style="{margin: '10px', background: '#fff', minHeight: '260px'}">
                    <Card>
                        <p slot="title">
                            <Icon @click.native="collapsedSider" :class="rotateIcon" :style="{margin: '0 20px',cursor: 'pointer'}" type="navicon-round" size="24"></Icon>
                        </p>
                        <br>
                        <Row :gutter="8">
                            <Col span="24">
                                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                                    <FormItem label="ID" prop="roadmapsid">
                                        <Input v-model="formValidate.roadmapsid" placeholder="ID不可编辑" disabled></Input>
                                    </FormItem>
                                    <FormItem label="时间节点" prop="thetime">
                                        <Input v-model="formValidate.thetime" placeholder="时间节点由系统自动记录" disabled></Input>
                                    </FormItem>
                                    <FormItem label="内容描述" prop="content">
                                        <!-- <Input v-model="formValidate.content" type="textarea" :autosize="{minRows: 12,maxRows: 25}" placeholder="请输入内容描述"></Input> -->
                                        <!-- <textarea class='tinymce-textarea' id="tinymceEditer"></textarea> -->
                                        <tinymceeditor id="tinymceEditer" v-model="formValidate.content" :init="editorInit"></tinymceeditor>
                                    </FormItem>
                                    <FormItem label="参与人" prop="participants">
                                        <!-- <Input v-model="formValidate.participants" type="textarea" :autosize="{minRows: 12,maxRows: 25}" placeholder="请输入参与人"></Input> -->
                                        <Transfer
                                            :data="data1"
                                            :target-keys="targetKeys1"
                                            :render-format="render1"
                                            :titles="titles"
                                            :list-style="listStyle"
                                            @on-change="handleChange1">
                                        </Transfer>
                                    </FormItem>
                                    <FormItem label="截图" prop="picture">
                                        <input id="picture" @change="handleChangePicture" name="picture" type="file"/>
                                    </FormItem>
                                    <FormItem label="压缩包" prop="zipfile">
                                        <input id="zipfile" @change="handleChangeZipfile" name="zipfile" type="file"/>
                                    </FormItem>
                                    <FormItem label="创建人" prop="creator">
                                        <Input v-model="formValidate.creator" placeholder="创建人由系统记录" disabled></Input>
                                    </FormItem>
                                    <FormItem label="序号" prop="sn">
                                        <Input type="number" v-model="formValidate.sn" placeholder="请输入序号"></Input>
                                    </FormItem>
                                    <FormItem label="确认状态" prop="signstatus">
                                        <Input v-model="formValidate.signstatus" placeholder="确认状态由系统自动判断" disabled></Input>
                                    </FormItem>
                                    <FormItem>
                                        <Button type="primary" @click="handleSubmit('formValidate')" :loading="save_loading">保存</Button>
                                        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                                    </FormItem>
                                </Form>
                            </Col>
                        </Row>
                    </Card>
                </Content>
            </Layout>
        </Layout>
    </div>
</template>

<script>
const {dialog} = require('electron').remote
const {ipcRenderer} = require('electron')
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import 'tinymce/skins/lightgray/skin.min.css'
import tinymceeditor from '@tinymce/tinymce-vue'
export default {
    name: 'roadmaps',
    components: {
        tinymceeditor
    },
    data () {
        return {
            showImgModal:false,
            imgModalPic:'',
            serverpath:'',
            keywords:'',
            timesdata: [],
            data1: [],//穿梭框
            targetKeys1: [],//穿梭框
            titles:['可选人', '参与人'],//穿梭框
            listStyle: {//穿梭框
                width: '170px',
                height: '240px'
            },
            save_loading:false,
            projectname:'',//当前项目名称
            currusername:'',
            formValidate: {
                roadmapsid:''
                ,thetime: ''
                ,content: ''
                ,participants: ''
                ,picture: ''
                ,zipfile: ''
                ,creator:''
                ,sn: 1
                ,signstatus:''
                ,picturefile:null//图片文件对象
                ,picture_path:''
                ,zipfilefile:null//压缩文件对象
                ,zipfile_path:''
                ,username:''//判断创建人
                ,oldparticipants:''
            },
            ruleValidate: {
                content: [
                    { required: true, message: '内容信息不能为空', trigger: 'blur'  }
                ]
            },
            editorInit: {
                skin_url: '../../../styles/tinymce/skins/lightgray',
                height: 250,
                menubar: "",
            },
            isCollapsed: false,
            key:'content',
            keywords:'',
            page: {
                total: 0,
                current: 1,
                pagesize: 1000,
                //原代码为  key: 'username', 但不符合通用规则,修改成id为key,如有需要可以改正
                key: 'thetime',
                order: 'desc',
                pagesizeopts: [5, 10, 20, 30, 40, 100]
            }
        };
    },
    computed: {
        rotateIcon () {
            return [
                'menu-icon',
                this.isCollapsed ? 'rotate-icon' : ''
            ];
        },
        menuitemClasses () {
            return [
                'menu-item',
                this.isCollapsed ? 'collapsed-menu' : ''
            ]
        }
    },
    methods: {
        handleShowImgModal (picurl) {
            this.showImgModal = true;
            this.imgModalPic = picurl;

        },
        collapsedSider () {
            this.$refs.side1.toggleCollapse();
        },
        handleSubmit (name) {
            this.save_loading = true;
            let self = this;
            let myname = localStorage.getItem('user');
            //修改别人的数据情况
            if(self.formValidate.roadmapsid
                && self.formValidate.roadmapsid.length>0
                && myname!=self.formValidate.creator){
                    self.save_loading = false;
                    self.$Message.error('请不要修改队友的数据!');
                    return false;
            }
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let title_str = '新增操作确认';
                    let content_str = '数据新增后只能修改，不能删除，确认新增数据吗？';
                    if(self.formValidate.roadmapsid && self.formValidate.roadmapsid.length>0){
                        title_str = '修改操作确认';
                        content_str = '确认修改数据吗？';
                    }
                    console.log(self.formValidate.participants);
                    console.log(self.formValidate.oldparticipants);
                    if(self.formValidate.participants != self.formValidate.oldparticipants){
                        content_str += '</br>调整参与人后，大家的确认状态会重置！';
                    }
                    this.$Modal.confirm({
                        loading:true,
                        title:title_str,
                        content:content_str,
                        onOk: function(){
                            let modal = this;
                            let param = new FormData(); //创建form对象
                            param.append('roadmapsid',self.formValidate.roadmapsid);//ID
                            if(self.formValidate.thetime) param.append('thetime',self.formValidate.thetime);
                            self.formValidate.content = tinymce.get('tinymceEditer').getContent();
                            param.append('content',self.formValidate.content);
                            param.append('participants',self.formValidate.participants);
                            param.append('picture',self.formValidate.picture);
                            param.append('zipfile',self.formValidate.zipfile);
                            param.append('creator',self.formValidate.creator);
                            param.append('sn',self.formValidate.sn);
                            param.append('signstatus',self.formValidate.signstatus);
                            param.append('fileofpic',self.formValidate.picturefile);//文件
                            param.append('fileofzip',self.formValidate.zipfilefile);//文件
                            param.append('projectname',self.projectname);//项目名称
                            self.$axios.post(self.$util.server+'roadmaps/save',  param, {
                                headers: {
                                    "authorization": localStorage.getItem("authorization"),
                                    "Content-Type":"multipart/form-data"
                                }
                            }).then(function(response) {
                                self.save_loading = false;
                                if(response.data.ok){
                                    modal.remove();
                                    self.$Message.success('保存成功!');
                                    self.handleSearch(1);
                                }else{
                                    self.$Message.error('保存失败，请检查!');
                                }
                            }).catch( function(response) {
                                self.$Message.error('保存失败，请检查输入内容!');
                                console.log(response)
                            });
                        },
                        onCancel:function(){
                            self.save_loading = false;
                        }
                    });
                } else {
                    self.save_loading = false;
                    self.$Message.error('内容验证不通过，请检查输入内容!');
                }
            })
        },
        handleFormdata (roadmapsid,thetime,content,participants,picture,zipfile,creator,sn,signstatus) {
            console.log(roadmapsid)
            this.formValidate.roadmapsid = roadmapsid;//ID
            this.formValidate.thetime = thetime;
            this.formValidate.content = content;
            tinymce.get('tinymceEditer').setContent(content);
            this.formValidate.participants = participants;
            this.formValidate.oldparticipants = participants;//保存原始数据
            this.getTargetKeys();//初始化穿梭框
            this.formValidate.picture = picture;
            this.formValidate.zipfile = zipfile;
            this.formValidate.creator = creator;
            this.formValidate.sn = sn;
            this.formValidate.signstatus = signstatus;
            this.formValidate.picture_path = this.$util.server + picture;
            this.formValidate.zipfile_path = this.$util.server + zipfile;
            if(!creator) this.formValidate.creator = localStorage.getItem('user');
            if(!signstatus) this.formValidate.signstatus = '未确认';
        },
        handleConfirm(roadmapsid,participants,myname){//参与人确认
            let self = this;
            this.$Modal.confirm({
                loading:true,
                title:'确认操作',
                content:'该操作<font>不可逆</font>,确定要继续吗？',
                onOk: function(){
                    let modal = this;
                    let participants_arr = participants.split(";");
                    let new_participants_arr = [];
                    let allconfirmed = '已确认';
                    for(let i=0;i<participants_arr.length;i++){
                        let participant = participants_arr[i].split("-");
                        let username = participant[0];
                        let status = participant[1];
                        if(username!=myname){
                            new_participants_arr.push(participants_arr[i]);
                        }else{
                            new_participants_arr.push(username+'-已确认');
                            status = '已确认';
                        }
                        if(status == '未确认') allconfirmed = '未确认';
                    }
                    self.$axios.post(self.$util.server+'roadmaps/sign?roadmapsid='+roadmapsid + '&signstatus='+allconfirmed+'&participants='+new_participants_arr.join(';'), {}, {
                        headers: {
                            "authorization": localStorage.getItem("authorization"),
                            "Content-Type":"application/json;charset=utf-8"
                        },
                    }).then(function(response) {
                        modal.remove();
                        if(response.data.ok>0) {
                            self.handleSearch(1);
                        }else{
                            self.$Message.error('修改失败!');
                        }
                    }).catch( function(response) {
                        console.log(response)
                    });
                }
            });
        },
        handleReset (name) {
            this.$refs[name].resetFields();
            this.formValidate.creator = localStorage.getItem('user');
            this.formValidate.signstatus = '未确认';
            this.targetKeys1 = [];
            this.formValidate.picturefile = null;//文件
            this.formValidate.zipfilefile = null;//文件
            document.getElementById("picture").value = null;
            document.getElementById("zipfile").value = null;
            //初始化form中的sn
            this.setMaxSn ();
        },
        handleSearch (topage) {
            //初始化列表
            let self = this;
            let size = this.page.pagesize;
            if(topage) this.page.current = topage;
            let page = this.page.current-1;
            let sort = this.page.key + ',' + this.page.order;
            if(this.page.order=='normal'){ sort = 'sn, asc';}
            let key = this.key;
            let keywords = this.keywords;

            this.$axios.get(self.$util.server+'roadmaps/pagedata', {
                params:{
                    size: size,
                    page: page,
                    sort: sort,
                    key: key,
                    keywords: keywords,
                    projectname: self.projectname
                },
                headers: {
                    "authorization": localStorage.getItem("authorization"),
                    "Content-Type":"application/json;charset=utf-8"
                }
            }).then(function(response) {
                if(response.data.total>0) {
                    self.timesdata = response.data.rows;
                    console.log(response.data.rows)
                    //初始化form中的sn
                    self.setMaxSn ();
                }else{
                    self.timesdata = [];
                }
            }).catch( function(response) {
                self.table.loading = false;//取消loading效果
                console.log(response)
            });
        },
        handleChangePicture(e) {
            let file=e.target.files.item(0);
            this.formValidate.picturefile = file;
        },
        handleChangeZipfile(e) {
            let file=e.target.files.item(0);
            this.formValidate.zipfilefile = file;
        },
        /******************************穿梭框开始****************************/
        getMockData () {
            let mockData = [];
            let alluser = JSON.parse(localStorage.getItem('alluser'));
            for (let i = 0; i < alluser.length; i++) {
                if(alluser[i].username!='banruo' && alluser[i].username!='demo'){
                    mockData.push({
                        key: alluser[i].username,
                        label: alluser[i].username,
                        description: alluser[i].username,
                        disabled: false
                    });
                }
            }
            this.data1 = mockData;
        },
        getTargetKeys () {
            let new_targetKeys1 = [];
            if(this.formValidate.participants){
                let participants = this.formValidate.participants.split(";");
                for(let i=0;i<participants.length;i++){
                    let participants_arr = participants[i].split("-");
                    let participants_username = participants_arr[0];
                    //let participants_status = participants_arr[1];
                    new_targetKeys1.push(participants_username);
                }
            }
            this.targetKeys1 = new_targetKeys1;
            console.log(this.targetKeys1)
        },
        render1 (item) {
            return item.label+' - '+item.description;
        },
        handleChange1 (newTargetKeys, direction, moveKeys) {
            console.log(newTargetKeys);
            console.log(direction);
            console.log(moveKeys);
            this.targetKeys1 = newTargetKeys;
            let new_participants = [];
            for(let i=0;i<newTargetKeys.length;i++){
                new_participants.push(newTargetKeys[i]+'-未确认');
            }
            this.formValidate.participants = new_participants.join(";");
        },
        /******************************穿梭框结束****************************/
        handleDownload (url) {
            ipcRenderer.send('downloadthefile',url)
        },
        handleOpenfile () {
            ipcRenderer.send('openfolder','__dirname')
        },
        setMaxSn () {
            let maxsn = 0;
            if(this.timesdata && this.timesdata.length>0){
                for(let i=0;i<this.timesdata.length;i++){
                    if(this.timesdata[i].sn > maxsn){
                        maxsn = this.timesdata[i].sn;
                    }
                }
            }
            this.formValidate.sn = maxsn+1;
        },
        handleInit () {
            //用户名
            console.log("localStorage.getItem('user'):"+localStorage.getItem('user'))
            this.currusername = localStorage.getItem('user');
            this.formValidate.username = localStorage.getItem('user');
            this.serverpath = this.$util.server;
            this.projectname = localStorage.getItem('projectname');
            //初始化查询
            this.handleSearch();
            //初始化穿梭框
            this.getMockData();
            this.getTargetKeys();
            //初始化表单
            this.formValidate.creator = localStorage.getItem('user');
            this.formValidate.signstatus = '未确认';
            //初始化编辑器
            let height = document.body.offsetHeight - 300;
            console.log(111111)
            tinymce.init({
                selector: "#tinymceEditer",
                branding: false,
                theme: "advanced", //advanced modern
                elementpath: false,
                height: height,
                language: "zh_CN.GB2312",
                menubar: "",
                mode : "textareas"
            });
            // tinymce.init({})

            //清除全部消息监听
            ipcRenderer.removeAllListeners('tips')
            //接收消息
            ipcRenderer.on('tips', (event, person) => {
                if(person && person.indexOf('下载成功，正在打开...')!=-1){
                    let content_arr = person.split(';');
                    this.$Message.info({content: content_arr[0], duration: 2})
                    ipcRenderer.send('openfolder',content_arr[1])
                    console.log(content_arr[1])
                }
            })
        }
    },
    mounted () {
        this.handleInit();
    }

};
</script>
